import { Component } from '@angular/core';
import { TabsPage } from '../tabs/tabs.component';
import { Storage } from '@ionic/storage';
import { Http } from '@angular/http';
import { AuthHttp } from 'angular2-jwt';
import { Config } from '../../providers/config';
import { LoginPage } from '../login/login.component';
import { AlertController, ViewController, NavController, Platform, LoadingController, App } from 'ionic-angular';
import _ from 'lodash';

@Component({
	selector: 'page-lock',
	templateUrl: 'lock.html',
})
export class LockPage {
	moa_page_name: any = "page-lock";
  moa_page_explain: any = "请绘制解锁图案";

	title = "请绘制解锁图案";

	isShowResetBtn = false;

	GestureLock = null;

	maxRetryTime = 3;

	retryTime = 0;

	// 定义每行多少个可选圆圈
	chooseType = 3;

	constructor(
		public alertController: AlertController,
		public viewCtrl: ViewController,
		public loadingController: LoadingController,
		public platform: Platform,
		public authHttp: AuthHttp,
		public appCtrl: App,
		public config: Config,
		public nav: NavController,
		public http: Http,
		public storage: Storage


	) {
		this.storage.set("isLock", true);
	}

	initLocker() {


		let that = this;
		window['GestureLock'] = function (obj) {
			this.height = obj.height;
			this.width = obj.width;
			this.chooseType = that.chooseType;
		};

		function getDis(a, b) {
			console.log('-------------getDis-------------');
			return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
		};

		window['GestureLock'].prototype.pickPoints = function (fromPt, toPt) {
			console.log('-------------pickPoints-------------');
			var lineLength = getDis(fromPt, toPt);
			var dir = toPt.index > fromPt.index ? 1 : -1;

			var len = this.restPoint.length;
			var i = dir === 1 ? 0 : (len - 1);
			var limit = dir === 1 ? len : -1;

			while (i !== limit) {
				var pt = this.restPoint[i];

				if (getDis(pt, fromPt) + getDis(pt, toPt) === lineLength) {
					this.drawPoint(pt.x, pt.y);
					this.lastPoint.push(pt);
					this.restPoint.splice(i, 1);
					if (limit > 0) {
						i--;
						limit--;
					}
				}

				i += dir;
			}
		}

		window['GestureLock'].prototype.drawCle = function (x, y) { // 初始化解锁密码面板
			console.log('-------------drawCle-------------');
			this.ctx.strokeStyle = '#fff';
			this.ctx.lineWidth = 3;
			this.ctx.beginPath();
			this.ctx.arc(x, y, this.r, 0, Math.PI * 2, true);
			this.ctx.closePath();
			this.ctx.stroke();
		}

		window['GestureLock'].prototype.drawPoint = function () { // 初始化圆心
			console.log('-------------drawPoint-------------');
			for (var i = 0; i < this.lastPoint.length; i++) {
				this.ctx.fillStyle = '#fff';
				this.ctx.beginPath();
				this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2, 0, Math.PI * 2, true);
				this.ctx.closePath();
				this.ctx.fill();
			}
		}
		window['GestureLock'].prototype.drawStatusPoint = function (type) { // 初始化状态线条
			console.log('-------------drawStatusPoint-------------');
			for (var i = 0; i < this.lastPoint.length; i++) {
				this.ctx.strokeStyle = type;
				this.ctx.beginPath();
				this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r, 0, Math.PI * 2, true);
				this.ctx.closePath();
				this.ctx.stroke();
			}
		}
		window['GestureLock'].prototype.drawLine = function (po, lastPoint) {// 解锁轨迹
			console.log('-------------drawLine-------------');
			this.ctx.beginPath();
			this.ctx.lineWidth = 3;
			this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);
			for (var i = 1; i < this.lastPoint.length; i++) {
				this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
			}
			this.ctx.lineTo(po.x, po.y);
			this.ctx.stroke();
			this.ctx.closePath();

		}
		window['GestureLock'].prototype.createCircle = function () {// 创建解锁点的坐标，根据canvas的大小来平均分配半径
			console.log('-------------createCircle-------------');
			var n = this.chooseType;
			var count = 0;
			this.r = this.ctx.canvas.width / (2 + 4 * n);// 公式计算
			this.lastPoint = [];
			this.arr = [];
			this.restPoint = [];
			var r = this.r;
			for (var i = 0; i < n; i++) {
				for (var j = 0; j < n; j++) {
					count++;
					var obj = {
						x: j * 4 * r + 3 * r,
						y: i * 4 * r + 3 * r,
						index: count
					};
					this.arr.push(obj);
					this.restPoint.push(obj);
				}
			}
			this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
			for (var i = 0; i < this.arr.length; i++) {
				this.drawCle(this.arr[i].x, this.arr[i].y);
			}
			//return arr;
		}
		window['GestureLock'].prototype.getPosition = function (e) {// 获取touch点相对于canvas的坐标
			console.log('-------------getPosition-------------');
			var rect = e.currentTarget.getBoundingClientRect();
			var po = {
				x: (e.touches[0].clientX - rect.left) * 2,
				y: (e.touches[0].clientY - rect.top) * 2
			};
			return po;
		}
		window['GestureLock'].prototype.update = function (po) {// 核心变换方法在touchmove时候调用
			console.log('-------------update-------------');
			this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);

			for (var i = 0; i < this.arr.length; i++) { // 每帧先把面板画出来
				this.drawCle(this.arr[i].x, this.arr[i].y);
			}

			this.drawPoint(this.lastPoint);// 每帧花轨迹
			this.drawLine(po, this.lastPoint);// 每帧画圆心

			for (var i = 0; i < this.restPoint.length; i++) {
				var pt = this.restPoint[i];

				if (Math.abs(po.x - pt.x) < this.r && Math.abs(po.y - pt.y) < this.r) {
					this.drawPoint(pt.x, pt.y);
					this.pickPoints(this.lastPoint[this.lastPoint.length - 1], pt);
					break;
				}
			}

		}
		window['GestureLock'].prototype.checkPass = function (psw1, psw2) {// 检测密码
			console.log('-------------checkPass-------------');
			var p1 = '',
				p2 = '';
			for (var i = 0; i < psw1.length; i++) {
				p1 += psw1[i].index + psw1[i].index;
			}
			for (var i = 0; i < psw2.length; i++) {
				p2 += psw2[i].index + psw2[i].index;
			}
			return p1 === p2;
		}
		window['GestureLock'].prototype.storePass = function (psw) {// touchend结束之后对密码和状态的处理
			console.log('-------------storePass-------------');
			if (this.pswObj.step == 1) {
				if (this.checkPass(this.pswObj.fpassword, psw)) {
					this.pswObj.step = 2;
					this.pswObj.spassword = psw;
					that.title = '手势密码保存成功';
					this.drawStatusPoint('#2CFF26');
					// window.localStorage.setItem('passwordxx', JSON.stringify(this.pswObj.spassword));
					that.storage.set('lockPassword', JSON.stringify(this.pswObj.spassword)).then(() => {
						// 如果密码保存成功，则调转到首页
						that.storage.set("isLock", false);
						if (that.viewCtrl.isOverlay) {
							that.viewCtrl.dismiss({
								isSet: true
							});
						} else {
							that.appCtrl.getRootNav().setRoot(TabsPage);
							// that.nav.setRoot(TabsPage);
						}
					});
				} else {
					that.title = '两次绘制不一致，请重新绘制';
					this.drawStatusPoint('red');
					delete this.pswObj.step;
				}
			} else if (this.pswObj.step == 2) {
				if (this.checkPass(this.pswObj.spassword, psw)) {
					that.title = '解锁成功';
					this.drawStatusPoint('#2CFF26');
					that.storage.set("isLock", false);
					if (that.viewCtrl.isOverlay) {
						that.viewCtrl.dismiss({});
					} else {
						that.appCtrl.getRootNav().setRoot(TabsPage);
						// that.nav.setRoot(TabsPage);
					}
					// 解锁成功，重置错误次数
					that.storage.set('lock-error-times', 0);
					// 如果解锁成功，则当前弹出框消失
				} else {
					this.drawStatusPoint('red');
					that.title = '解锁失败';
					//解锁失败5次跳转登录页面
					that.checkLockErrorTimes();

				}
			} else {
				this.pswObj.step = 1;
				this.pswObj.fpassword = psw;
				that.title = '请再次绘制解锁图案';
			}

		}
		window['GestureLock'].prototype.makeState = function () {
			console.log('-------------makeState-------------');
			if (this.pswObj.step == 2) {
				that.isShowResetBtn = true;
				//document.getElementById('chooseType').style.display = 'none';
				that.title = '请使用手势密码登陆';
			} else if (this.pswObj.step == 1) {
				//document.getElementById('chooseType').style.display = 'none';
				that.isShowResetBtn = false;
			} else {
				that.isShowResetBtn = false;
				//document.getElementById('chooseType').style.display = 'block';
			}
		}
		window['GestureLock'].prototype.setChooseType = function (type) {
			console.log('-------------setChooseType-------------');
			let chooseType = type;
			window['GestureLock'].init();
		}
		window['GestureLock'].prototype.updatePassword = function () {
			that.storage.remove('lockPassword');
			this.pswObj = {};
			that.title = '绘制解锁图案';
			this.reset();
		}
		window['GestureLock'].prototype.initDom = function () {
			console.log('-------------initDom-------------');
			var canvasWidth = window.innerWidth;
			var wrap = document.createElement('div');
			wrap.id = 'lock-gesture-content';
			var str = '<canvas id="lock-canvas" width="' + canvasWidth * 2 + '" height="' + canvasWidth * 2 + '" style="width:' + canvasWidth + 'px;height: ' + canvasWidth + 'px;"></canvas>';
			wrap.innerHTML = str;
			if (!document.getElementById("lock-gesture-content")) {
				document.getElementsByTagName("page-lock")[0].appendChild(wrap);
			}
		}
		window['GestureLock'].prototype.init = function () {
			console.log('-------------init-------------');
			this.initDom();
			let _that = this;
			that.storage.get('lockPassword').then(function (password) {
				if (password) {
					_that.pswObj = {
						step: 2,
						spassword: JSON.parse(password)
					}
				} else {
					_that.pswObj = {};
				}
				_that.lastPoint = [];
				_that.makeState();
				_that.touchFlag = false;
				_that.canvas = document.getElementById('lock-canvas');
				_that.ctx = _that.canvas.getContext('2d');
				_that.createCircle();
				_that.bindEvent();
			});
			// this.pswObj = window.localStorage.getItem('passwordxx') ? {
			// 	step: 2,
			// 	spassword: JSON.parse(window.localStorage.getItem('passwordxx'))
			// } : {};
		}
		window['GestureLock'].prototype.reset = function () {
			console.log('-------------reset-------------');
			this.makeState();
			this.createCircle();
		}
		window['GestureLock'].prototype.bindEvent = function () {
			console.log('-------------bindEvent-------------');
			var self = this;
			this.canvas.addEventListener("touchstart", function (e) {
				e.preventDefault();// 某些android 的 touchmove不宜触发 所以增加此行代码
				var po = self.getPosition(e);
				for (var i = 0; i < self.arr.length; i++) {
					if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {

						self.touchFlag = true;
						self.drawPoint(self.arr[i].x, self.arr[i].y);
						self.lastPoint.push(self.arr[i]);
						self.restPoint.splice(i, 1);
						break;
					}
				}
			}, false);
			this.canvas.addEventListener("touchmove", function (e) {
				if (self.touchFlag) {
					self.update(self.getPosition(e));
				}
			}, false);
			this.canvas.addEventListener("touchend", function (e) {
				if (self.touchFlag) {
					self.touchFlag = false;
					self.storePass(self.lastPoint);
					setTimeout(function () {

						self.reset();
					}, 300);
				}
			}, false);
			// document.addEventListener('touchmove', function(e) {
			// 	e.preventDefault();
			// }, false);
		}
	}

	resetPassword() {
		let that = this;
		this.storage.remove('lockPassword');
		this.storage.set("isLock", false);
		this.storage.remove('id_token').then(() => {
			if (that.viewCtrl.isOverlay) {
				that.viewCtrl.dismiss({});
			}
			that.appCtrl.getRootNav().setRoot(LoginPage);
		});
		// 重置手势密码错误次数
		that.storage.set('lock-error-times', 0);
	}

	closeLock() {
		this.storage.set("isLock", false);
		this.viewCtrl.dismiss({
			isSet: false
		});
	}

	loginByPassword() {
		this.storage.set("isLock", false);
		if (this.viewCtrl.isOverlay) {
			this.viewCtrl.dismiss({});
		}
		this.appCtrl.getRootNav().setRoot(LoginPage, {
			isCheckLockPassword: false
		});
	}

	/**
	 * 检查解锁错误超过五次，
	 */
	checkLockErrorTimes() {
		let that = this;
		this.storage.get("configs").then(configs => {
			console.log('------------configs----------------')
			//console.log(configs);
			if (configs && configs.length > 0) {
				let gestureLock: any = _.find(configs, {
					name: "gestureLock"
				})['json'];

				that.storage.get('lock-error-times').then((val) => {
					if (val == (gestureLock.count - 1)) {
						that.resetPassword();
						that.lockErrorAlert(gestureLock.count);
					} else {
						val = val + 1;
						that.storage.set('lock-error-times', val);
					}
				});
			}

		});


	}

	/**
	  * 解锁错误超过五次，跳出提示框
	  */
	lockErrorAlert(count) {
		let that = this;
		let alert = that.alertController.create({
			title: '提示',
			message: '手势密码错误累积达到' + count + '次，请使用账号密码登录!',
			buttons: ['确认']
		});
		alert.present()
	}

	ionViewDidEnter() {
		let that = this;
		try {
			this.initLocker();
			// setTimeout(function() {
			that.GestureLock = new window['GestureLock']({}).init();
			// }, 200);
		} catch (err) {
			window.location.href = "";
		}
	}

}
